package com.wedo.mall.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.e.library.activity.EActivity;
import com.e.library.entity.User;
import com.e.library.http.EObserver;
import com.e.library.http.EResponse;
import com.e.library.listener.EListener;
import com.e.library.utils.EUtils;
import com.e.library.utils.EViewUtils;
import com.facebook.FacebookSdk;
import com.wedo.mall.BuildConfig;
import com.wedo.mall.R;
import com.wedo.mall.activity.login.WLogin;
import com.wedo.mall.activity.register.RegisterActivity;
import com.wedo.mall.adapter.AccountAdapter;
import com.wedo.mall.db.DBHelper;
import com.wedo.mall.entity.Account;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import io.reactivex.Observable;

/**
 * Created by lxy on 2017/6/10.
 */

public class LoginActivity extends EActivity {

    /**登录入口*/
    public static final String EXTRA_ENDPOINT = "endpoint";
    public static final int ENDPOINT_SPLASH = 0;//从启动页跳转的登录，登录成功跳转到主界面
    public static final int ENDPOINT_MAIN = 1;//从主界面或者其他页面跳转的登录，登录成功返回用户
    private int endpoint = ENDPOINT_SPLASH;

    @BindView(R.id.et_username) EditText et_username;
    @BindView(R.id.et_password) EditText et_password;
    @BindView(R.id.rv_account)  RecyclerView rv_account;
    private AccountAdapter mAccountAdapter;

    private WLogin wLogin;

    @Override
    protected int layout() {
        return R.layout.activity_login;
    }

    @Override
    protected void onActivityCreated(Bundle state) {

        //FacebookSdk.sdkInitialize(this);
        endpoint = getIntent().getIntExtra(EXTRA_ENDPOINT,0);
        wLogin = WLogin.with().listener(new WLogin.LoginListener() {

            @Override
            public void loading() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        LoginActivity.this.loading();
                    }
                });
            }

            @Override
            public void successful(User user) {

                if(!WLogin.isAuth(LoginActivity.this)) {
                    /**------账号密码登录，保存登录记录-----**/
                    String account = et_username.getText().toString();
                    String password = et_password.getText().toString();
                    DBHelper.with(LoginActivity.this).onLoginSuccessful(account,password,user.headimgurl);
                }

                dismiss();
                if (endpoint ==ENDPOINT_SPLASH){
                    toActivity(MainActivity.class);
                    defaultFinish();
                }else if (endpoint == ENDPOINT_MAIN){
                    Intent intent = new Intent();
                    intent.putExtra("user",user);
                    setResult(RESULT_OK,intent);
                    defaultFinish();
                }

            }

            @Override
            public void failure(final String msg) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        toast(msg);
                        dismiss();
                    }
                });
            }
        });

        tel();

        rv_account.setHasFixedSize(true);
        EViewUtils.vertical(rv_account);
        mAccountAdapter = new AccountAdapter(this,new ArrayList<Account>());
        rv_account.setAdapter(mAccountAdapter);
        mAccountAdapter.setItemClickListener(new EListener<Account>() {
            @Override
            public void onInvoked(View view, Account data, int position) {
                et_username.setText(data.username);
                et_password.setText(data.password);
                rv_account.setVisibility(View.GONE);
            }
        });

        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
            return;
        }

        if(BuildConfig.DEBUG) {
//            et_username.setText("15002023601");
//            et_password.setText("Lawrence123456");
//            et_username.setText("15018402350");
//            et_password.setText("lin123456");
//            et_username.setText("13610285926");
//            et_password.setText("qwe12");
            //DBHelper.with(this).testInsert();
            et_password.setText("12345678abc");
            //et_username.setText("hui_67@wedo.my");
            et_username.setText("mike.neoh714@gmail.com");

            //et_username.setText("mike.neoh67@hotmail.com");
        }
    }

    @OnClick(R.id.btn_login)
    protected void onLoginClick(){
        rv_account.setVisibility(View.GONE);
        String account = et_username.getText().toString();
        if (TextUtils.isEmpty(account)){
            toast(R.string.login_id_hint);
            return;
        }

        if (!EUtils.isMobile(account)){
            if (!EUtils.isEmail(account)){
                toast(R.string.login_id_invalid);
                return;
            }
        }

        String password = et_password.getText().toString();
        if (TextUtils.isEmpty(password)){
            toast(R.string.login_password_hint);
            return;
        }

        if (password.length() <6 || password.length() >12){
            toast(R.string.login_password_invalid);
            return;
        }

        loading();
        wLogin.login(this,account,password);

    }

    @OnClick({R.id.tv_login_facebook,R.id.tv_login_wechat})
    protected void onAuthClick(View view){
        switch (view.getId()){
            case R.id.tv_login_facebook:
                wLogin.facebook(this);
                break;
            case R.id.tv_login_wechat:
                wLogin.wechat(this);
                break;
        }
    }

    @OnClick(R.id.btn_register)
    protected void onRegisterClick(){
        toActivity(RegisterActivity.class);
    }

    @OnClick(R.id.btn_tourist)
    protected void onTouristClick(){
        toActivity(MainActivity.class);
        defaultFinish();
    }

    @OnClick(R.id.btn_forgot)
    protected void onForgotActivity(){
        toActivity(ForgotActivity.class);
    }

    @OnClick(R.id.ll_root)
    protected void onRootClick(){
        hideKeybord();
        rv_account.setVisibility(View.GONE);
    }

    @OnClick(R.id.btn_help)
    protected void onHelpClick(){
        requestPhoneCall(tel);
    }

    @OnClick(R.id.et_username)
    protected void onAccountClick(){
        rv_account.setVisibility(View.VISIBLE);
        mAccountAdapter.refresh(DBHelper.with(this).accounts());
    }

    @OnTextChanged(R.id.et_username)
    protected void onAccountChange(Editable input){

        if (input == null){
            rv_account.setVisibility(View.GONE);
            return;
        }

        String txt = input.toString();
        if (TextUtils.isEmpty(txt)){
            rv_account.setVisibility(View.GONE);
            return;
        }

        List<Account> list = DBHelper.with(this).onTextChange(txt);
        if (EUtils.isEmpty(list)){
            rv_account.setVisibility(View.GONE);
            return;
        }

        rv_account.setVisibility(View.VISIBLE);
        mAccountAdapter.refresh(list);
    }

    @Override
    protected void onDestroy() {
        wLogin.onDestroy();
        wLogin = null;
        super.onDestroy();
    }

    private String tel;
    private void tel(){
        Observable<EResponse> observable = api().tel(new HashMap<String, String>(1));
        observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                tel = response.string("list");
            }

            @Override
            public void failure(String msg) {

            }
        });
    }

    public static final int REQ_PHONE_CALL = 104;
    public  void requestPhoneCall(String phone){
        if(TextUtils.isEmpty(phone)) {
            toast(R.string.consult_phone_invalid);
            return;
        }

        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE},REQ_PHONE_CALL);
            return;
        }
        phoneCall(phone);
    }

    public void phoneCall(String phone){
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phone));
        startActivity(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQ_PHONE_CALL){
            if (grantResults.length >0){
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        wLogin.onActivityResult(requestCode,resultCode,data);
        super.onActivityResult(requestCode, resultCode, data);
    }

}
